package com.ztao.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.ztao.pojo.ApUserSearch;
import com.ztao.pojo.dto.HistorySearchDto;
import com.ztao.service.ApUserSearchService;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    /**
     * 添加搜索记录
     *
     * @param userId
     * @param keyword
     */
    @Resource
    private MongoTemplate mongoTemplate;
    @Async
    @Override
    public void insert(String userId, String keyword) {
        //校验参数
        //判断当前用户的搜索关键字是都存在
        Query query=new Query(Criteria
                .where("userId")
                .is(userId)
                .and("keyword")
                .is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class, "ap_user_search");
        //如果关键字存在，更新创建时间
        if(apUserSearch!=null){
            Update update=new Update();
            update.set("createdTime",new Date());
            mongoTemplate.updateFirst(query,update, ApUserSearch.class);
            return;
        }
        //如果关键字不存在
        //判断是否大于10条，如果小于10条执行添加操作
        Query query1=new Query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class, "ap_user_search");
        System.out.println("条数=======》"+apUserSearchList.size());

        ApUserSearch apUserSearch1=new ApUserSearch();
        apUserSearch1.setUserId(userId);
        apUserSearch1.setKeyword(keyword);
        apUserSearch1.setCreatedTime(new Date());
        if(apUserSearchList==null||apUserSearchList.size()<10){
            //执行添加操作
            mongoTemplate.save(apUserSearch1);
        }else {
            //已经有10条记录了，吧最后一条记录替换到
            ApUserSearch lastSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id")
                    .is(lastSearch.getId()))
                    ,apUserSearch1);
        }
    }

    /**
     * 根据userId查询
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult findUserSearch(String userId) {
        Query query = new Query(Criteria.where("userId").is("4"));
        //按照时间倒叙
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 根据id删除
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteById(HistorySearchDto dto) {
        if(dto.getId()==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除
        mongoTemplate.remove(Query.query(Criteria
                .where("id")
                .is(dto.getId())),
                ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
